package com.example.yls.demoa;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * Created by yls on 2018/12/3.
 */

public class StuContentProvider extends ContentProvider{
    private StuOpenHelper stuOpenHelper;
    private static final String AUTOHOTITY ="com.gdcp.student";//授权
    private static UriMatcher matcher =new UriMatcher(UriMatcher.NO_MATCH);
    static {
        matcher.addURI(AUTOHOTITY,"student",1);
        matcher.addURI(AUTOHOTITY,"score",2);
    }
    @Override
    public boolean onCreate() {
        stuOpenHelper = new StuOpenHelper(getContext(),"stu.db",null,1);
        return true;
    }
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        SQLiteDatabase database = stuOpenHelper.getWritableDatabase();
        switch (matcher.match(uri)){
            case 1:
                database.insert("student",null,contentValues);
                break;

            case 2:
                database.insert("score",null,contentValues);
                database.close();
                break;
        }
        return null;
    }
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings,
                        @Nullable String where, @Nullable String[] whereArgs, @Nullable String order) {
        SQLiteDatabase sqLiteDatabase = stuOpenHelper.getReadableDatabase();
        switch (matcher.match(uri)){
            case 1:

              Cursor cursor1 =sqLiteDatabase.query("student",strings,where,whereArgs,null,null,order);
                return cursor1;
            case 2:
                Cursor cursor2 =sqLiteDatabase.query("score",strings,where,whereArgs,null,null,order);
                return cursor2;
            case 3:
                break;
        }
        return null;
    }
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    @Override
    //uri表名
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        switch (matcher.match(uri)){
            case 1:
                SQLiteDatabase sqLiteDatabase  = stuOpenHelper.getWritableDatabase();
                int rows = sqLiteDatabase.delete("student",selection,selectionArgs);
                sqLiteDatabase.close();
                return rows;
            case 2:
                break;
        }
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }
}
